package cn.zhz.office.convert.pdf.util;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ZipUtil;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author ZHZ
 * @since 2023-01-31
 * pdf转换工具类
 */
public class PdfConvertUtil {


    /**
     * 转为image
     *
     * @param pdfInputStream
     * @param imageOutputStream
     */
    public static void toImage(InputStream pdfInputStream, OutputStream imageOutputStream) throws IOException {

        PDDocument pd = PDDocument.load(pdfInputStream);
        PDFRenderer pdfRenderer = new PDFRenderer(pd);

        // 存放图片的文件夹
        String uuid = UUID.fastUUID().toString();
        String tmpDirPath = FileUtil.getTmpDirPath() + uuid + File.separator;
        String tmpImagePath = tmpDirPath + "image" + File.separator;
        File tmpImageFolder = FileUtil.mkdir(tmpImagePath);

        for (int page = 0; page < pd.getNumberOfPages(); ++page) {
            // 像素点数dpi可设置
            BufferedImage image = pdfRenderer.renderImage(page);
            //将图片数据保存为PNG格式文档
            File file = new File(tmpImagePath + page + ".png");
            ImageIO.write(image, ImgUtil.IMAGE_TYPE_PNG, file);
        }

        File zipFile = ZipUtil.zip(tmpImageFolder);
        FileUtils.copyFile(zipFile, imageOutputStream);
        // 删除临时文件夹
        FileUtil.del(tmpDirPath);

    }

}
